package com.bw.mallshop.mvvm.model;

import com.bw.common.BaseApplication;
import com.bw.common.entity.BaseEntity;
import com.bw.common.mvvm.model.BaseModel;
import com.bw.common.network.HttpType;
import com.bw.common.network.RetrofitFactory;
import com.bw.mallshop.App;
import com.bw.mallshop.entity.AddCarEntity;
import com.bw.mallshop.entity.CarListEntity;
import com.bw.mallshop.entity.HomeDedtailEntity;
import com.bw.mallshop.entity.HomeGoodsEntity;
import com.bw.mallshop.entity.HomeLoadEntity;
import com.bw.mallshop.repository.ApiService;

import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.annotations.NonNull;

public class GoodsValuesModel extends BaseModel {

    //推荐商品上拉加载更多
    public Observable<BaseEntity>requestLoad(Map<String,Object>parames){
        Observable<HomeLoadEntity>observable = RetrofitFactory.factory(HttpType.TOKENSIGN)
                .createRetrofit().create(ApiService.class).loadHomeGoods(createBody(parames));
        return changeObservable(observable);
    }
    //获取商品详情以及推荐商品接口->rxjava merge
    public Observable<BaseEntity>requestAll(Map<String,Object>...parames){
        //生成获取商品详情接口被观察者任务
        Observable<HomeDedtailEntity>dedtailObservable = RetrofitFactory.factory(HttpType.TOKENSIGN)
                .createRetrofit().create(ApiService.class).requestHomeDetail(createBody(parames[0]));
        //生成获取推荐商品被观察者任务
        Observable<HomeGoodsEntity>goodsObservable=RetrofitFactory.factory(HttpType.TOKENSIGN)
                .createRetrofit().create(ApiService.class).requestHomeGoods(createBody(parames[1]));
        return mergeObservable(dedtailObservable,goodsObservable);
    }
    //加入在线购物车
    public Observable<BaseEntity>requestAddCar(Map<String,Object>parames){
        Observable<AddCarEntity>observable = RetrofitFactory.factory(HttpType.TOKEN)
                .createRetrofit().create(ApiService.class)
                .requestAddCar(createBody(parames));
        return changeObservable(observable);
    }
    //加入离线购物车
    public Observable<BaseEntity>insertyCarDao(CarListEntity.Values values){
        Observable<CarListEntity>observable=Observable.create(new ObservableOnSubscribe<CarListEntity>(){

            @Override
            public void subscribe(@NonNull ObservableEmitter<CarListEntity> emitter) throws Exception {
                App app = (App) BaseApplication.getInstance();
                app.db.carDao().insertCar(values);
                CarListEntity entity = new CarListEntity();
                entity.message = "添加成功";
                entity.status = 0;
                emitter.onNext(entity);
                emitter.onComplete();
            }
        });
        return changeObservable(observable);
    }
}
